package com.wanrui.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello shiro");
        return "index";
    }


    @RequestMapping("/add")
    public String add(Model model){
        return "add";
    }


    @RequestMapping("/unAuthor")
    @ResponseBody
    public String unAuthor(Model model){
        return "unAuthor";
    }

    @RequestMapping("update")
    public String update(Model model){
        return "update";
    }

    @RequestMapping("/login")
    public String update(@RequestParam("user") String user, @RequestParam("pwd") String pwd,Model model){
        // 获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        // 封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(user, pwd);
        // 执行登录
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {  // 用户名不存在异常
            model.addAttribute("msg", "用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg", "密码错误");
            return "login";
        }
        model.addAttribute("msg", "登录成功");
//        return "indexHome";
        return "index";
    }

    @RequestMapping("/toLogin")
    public String update(){
        return "login";
    }
}
